/**----------------------------------------------------------*/
/** JS:  cmi_admin_list.js（权限管理--管理员信息）            */
/**----------------------------------------------------------*/

var tipc = 'ADMIN_INFO';
var st_power = 'ADMIN_INFO_POWER';
var st_role = 'ADMIN_POWER_CMI_ROLE';
var win = null;
var pref = 'SYS_';
var select_record = null;

$(function(){
	try {
		loadMemberPanel();
	} catch (e) {
		showJsException(e,"数据加载失败!");
	}	
});

var enableEidt = function(aid) {
	if(aid == myId) {
		MyUtils.info("存在您无权操作的数据!");
		return false;
	}
	return true;
};

var loadMemberPanel = function() {
	var columns = [  {field : 'aid',title : '用户名',width : 150,align : 'center',formatter:function(value){return MyUtils.valueAlign(value,"left");}}
					,{field : 'amail',title : 'Email地址',width : 250,align : 'center',formatter:function(value){return MyUtils.valueAlign(value,"left");}}
					,{field : 'acreate',title : '加入时间',width : 250,align : 'center',formatter:function(value){return MyUtils.valueAlign(value,"center");}}
					,{field : 'alastLogin',title : '最后登录时间',width : 250,align : 'center',formatter:function(value){return MyUtils.valueAlign(value,"center");}}
				];
	var pam = {rows:200,page:1,qr:"[]",st:tipc,sco:'',dc:Dmlx.sort.desc};
	MyUtils.createPaginPanelWithQueryparams('dataPanel',null,Dmlx._hFrozenColumns,columns,toolbars,dbclick, panel,null);
	$('#dataPanel').datagrid({
		url:"impl_search/commonsPaginSearch.ajax",
		queryParams:pam,
		pagination:false,
		fitColumns:true
	});
};

var dbclick = function(index,row){
	$('#dataPanel').datagrid("clearSelections");
	$('#dataPanel').datagrid("selectRow",index);
	modify();
};

var add = function(){
	try {
		var div = getEditDiv(null);
		win = MyUtils._getToolbarWin("dataPanel", "dateEdit", div, submitAdd, panel + "--添加","保存提交");
		win.window({
			width:450,
			height:270,
			modal: true
		});
		repainSelectRole(null);
	} catch (e) {
		showJsException(e);
	}
};

var submitAdd = function() {
	try {
		var dt = editValidator(true);
		if(dt != null) {
			var data = {dt:dt,st:tipc};
			MyUtils.openMask(_msg_process,win);
			submitDate("impl_add/backAdd.adm",data,1);
		}
	} catch (e) {
		MyUtils.hiddenMask(win);
		showJsException(e,_msg_fail);
	}
};

var modify = function() {
	var record = datagridOneRow('dataPanel');
	if(record == null) {
		return;
	}
	if(enableEidt(record.aid)) {
		try {
			var div = getEditDiv(record);
			win = MyUtils._getToolbarWin("dataPanel", "dateEdit", div, submitModify, panel +"--修改","保存提交");
			win.window({
				width:450,
				height:330,
				modal: true
			});
			repainSelectRole(record);
		} catch (e) {
			showJsException(e);
		}
	}
};

var submitModify = function() {
	try {
		var dt = editValidator(false);
		if(dt != null) {
			var data = {dt:dt,st:tipc,qy:"[]"};
			$.messager.confirm(_msg_sys,MyUtils.valueAlign(_modify_confirm,"left"), function(r) {
				if(r) {
					MyUtils.openMask(_msg_process,win);
					submitDate("impl_modify/backModify.adm",data,2);
				}
			});
		}
	} catch (e) {
		MyUtils.hiddenMask(win);
		showJsException(e,_msg_fail);
	}
};

var remove = function() {
	var rows = $('#dataPanel').datagrid("getSelections");
	if(rows.length == 0) {
		MyUtils.waring(_empty_select);
		return;
	}
	try {
		if (rows) {
			$.messager.confirm(_msg_sys,MyUtils.valueAlign(_remove_confirm,"left"), function(r) {
				if (r) {
					var ids = new Array();
					var names = new Array();
					var canDo = true;
					for(var i = 0; i < rows.length; i++) {
						ids.push(rows[i].uuid);
						names.push(rows[i].aid);
						canDo = enableEidt(rows[i].aid);
						if(!canDo) {
							break;
						}
					}
					if(canDo) {
						var data = {data:ids.toString(),st:tipc,msg:names.toString()};
						MyUtils.openMask(_msg_process,$('#t2'));
						submitDate("impl_remove/backRemove.adm",data,3);
					}
				}
			});
		}
	} catch (e) {
		MyUtils.hiddenMask('#t2');
		showJsException(e,_msg_fail);
	}
};

var setPower = function(){
	var record = datagridOneRow('dataPanel');
	if(record == null) {
		return;
	}
	if(enableEidt(record.aid)) {
		try{
			loadPowerDiv(record.aid);
			MyUtils.openMask(_msg_process,$('#list-div'));
			var pt = {userId:record.aid};
			MyUtils.sendPost("impl_search/searchTreeList.ajax",{qr:"[]",st:tipc,pt:MyUtils.toJsonStr(pt)},function(rets){
				try{
					var error = MyUtils.toJsonObject(rets);
					loadPower(error);
					MyUtils.hiddenMask($('#list-div'));
				} catch (e) {
					MyUtils.hiddenMask($('#list-div'));
					showJsException(e,"页面信息加载失败!");
				}
			});
		} catch (e) {
			MyUtils.hiddenMask(win);
			MyUtils.error(_msg_fail);
		}
	}
};

var viewOperatorLog = function(){
	var url = 'dispatch.adm?url=/dispatch.adm&p=web/pages/back/cmi_power/cmi_admin_log&menuId=13';
	location.replace(url);
};

var loadPowerDiv = function(aid){
	$('#t2').empty();
	var powerDiv ='<div id="list-div" class="list-div">'
			+'<div style="border-bottom: 1px solid gray;padding:5px;">'
			+'<div style="margin-left: 85%;"> '
			+'<span><a id="_back_role" icon="icon-back" href="javascript:void(0)">管理员信息列表</a></span>'
			+'</div>'
			+'</div>'
			+'<div id="empty_power" style="display: none;"><h2 class="require-field">没有可以设置的权限</h2></div>'
			+'<input type="hidden" id="opUser" value="'+aid+'">'
			+'<table id="list-table" cellspacing="0"><tbody></tbody></table>'
			+'</div>'
			+'<div style="position:fixed;bottom: 10px;width:100%;border-top: 1px solid gray;padding:5px;"> '
			+'<span style="margin-left: 85%;"><a id="_save_role" icon="icon-save" href="javascript:void(0)" >保存提交</a></span>'
			+'</div>'
			+'</div>';
	$('#t2').append(powerDiv);
	
	//管理员权限设置
	$('#_back_role').linkbutton({
		plain : true
	}).click(function(){
		reopenDatepanel();
	});
	
	//保存权限
	$('#_save_role').linkbutton({
		plain : true
	}).click(function(){
		try{
			var checks = $('input[checked="checked"]');
			var ids = new Array();
			for(var i =0 ;i < checks.length; i++) {
				ids.push(checks[i].value);
			}
			var users = {
				 aid:$('#opUser').val()
				,powerStr:ids.toString()
			};
			MyUtils.openMask(_msg_process,$('#list-div'));
			MyUtils.sendPost("impl_modify/backModify.adm",{dt:MyUtils.toJsonStr(users),st:st_power,qy:"[]"},function(rets){
				MyUtils.hiddenMask($('#list-div'));
				try{
					var res = MyUtils.toJsonObject(rets);
					if(res.error == '0') {
						MyUtils.info(res.msg);
						reopenDatepanel();
					} else {
						MyUtils.error(res.msg);
					}
				} catch (e) {
					MyUtils.hiddenMask($('#list-div'));
					showJsException(e,"页面信息加载失败!");
				}
			});
			
		} catch (e) {
			MyUtils.hiddenMask($('#list-div'));
			MyUtils.error(_msg_fail);
		}
	});
};

var loadPower = function(error){
	if(error.code == 0) {
		//加载所有权限
		if(!MyUtils.isEmpty(error.system)){
			$('#empty_power').hide();
			$('#list-table tbody').empty();
			$('#list-table').show();
			
			//屏蔽系统
			var children = error.system[0].children;
			var system = "";
			for(var i = 0; i < children.length; i++) {
				system +='<tr>' + createMenu(pref,children[i]) + "</tr>";
			}
			$('#list-table tbody').append(system);
		} else {
			$('#list-table').hide();
			$('#list-table tbody').empty();
			$('#empty_power').show();
		}
		
		//选择用户拥有的权限
		if(!MyUtils.isEmpty(error.datas)){
			var ids = new Array();
			for(var i = 0; i < error.datas.length; i++) {
				var menu = error.datas[i];
				ids.push("#"+pref + menu.id + "_");
				
				for(var j = 0; j < menu.children.length; j++){
					var menuItem = menu.children[j];
					ids.push("#"+pref + menu.id + "_" + menuItem.id + "_");
					
					for(var v = 0; v < menuItem.children.length; v++){
						var func = menuItem.children[v];
						ids.push("#"+pref + menu.id + "_" + menuItem.id + "_" + func.id + "_");
					}
				}
			}
			if(ids.length > 0) {
				$(ids.toString()).attr("checked",true);
			}
		}
	} else {
		MyUtils.error("页面信息加载失败!");
	}
};

var Callback_add = function(msg) {
	try{
		MyUtils.hiddenMask(win);
		var res = MyUtils.toJsonObject(msg);
		if(res.error == '0') {
			if(win)win.window('close');
			var record = res.saveRecord;
			var pt = {
					 roleId:record.roleId
					,userId:record.aid
			};
			loadPowerDiv(record.aid);
			MyUtils.openMask(_msg_process,$('#list-div'));
			MyUtils.sendPost("impl_search/searchTreeList.ajax",{qr:"[]",st:tipc,pt:MyUtils.toJsonStr(pt)},function(rets){
				try{
					var error = MyUtils.toJsonObject(rets);
					loadPower(error);
					MyUtils.hiddenMask($('#list-div'));
				} catch (e) {
					MyUtils.hiddenMask($('#list-div'));
					showJsException(e,"页面信息加载失败!");
				}
			});
		} else {
			MyUtils.error(res.msg);
		}
	} catch (e) {
		MyUtils.hiddenMask(win);
		MyUtils.hiddenMask($('#list-div'));
		MyUtils.error(_msg_fail);
	}
};

var Callback_modify = function(msg) {
	try{
		MyUtils.hiddenMask(win);
		var res = MyUtils.toJsonObject(msg);
		if(res.error == '0') {
			if(win)win.window('close');
			var record = res.saveRecord;
			var pt = {
					 roleId:record.roleId
					,userId:record.aid
			};
			
			loadPowerDiv(record.aid);
			MyUtils.openMask(_msg_process,$('#list-div'));
			MyUtils.sendPost("impl_search/searchTreeList.ajax",{qr:"[]",st:tipc,pt:MyUtils.toJsonStr(pt)},function(rets){
				try{
					var error = MyUtils.toJsonObject(rets);
					loadPower(error);
					MyUtils.hiddenMask($('#list-div'));
				} catch (e) {
					MyUtils.hiddenMask($('#list-div'));
					showJsException(e,"页面信息加载失败!");
				}
			});
		} else {
			MyUtils.error(res.msg);
		}
	} catch (e) {
		MyUtils.hiddenMask($('#list-div'));
		MyUtils.hiddenMask(win);
		MyUtils.error(_msg_fail);
	}
};
var Callback_remove = function(msg) {
	try{
		MyUtils.hiddenMask($('#t2'));
		var res = MyUtils.toJsonObject(msg);
		if(res.error == '0') {
			MyUtils.info(res.msg);
			$('#dataPanel').datagrid("clearSelections");
			$('#dataPanel').datagrid("reload");
		} else {
			MyUtils.error(res.msg);
		}
	} catch (e) {
		MyUtils.hiddenMask($('#t2'));
		MyUtils.error(_msg_fail);
	}
};

var submitDate = function(url,data,what) {
	MyUtils.sendPost(url,data,function(msg){
		if(what == 1) {
			Callback_add(msg);
		} else if (what == 2) {
			Callback_modify(msg);
		} else if (what == 3) {
			Callback_remove(msg);
		}
	});
};

/********************************************** 方法调用*****************************/
var getEditDiv = function(record) {
	var div= '<table cellspacing="2" cellpadding="6" id="dateEdit">'
			+'<tbody>'
				+'<tr>'
					+'<th align="right">用户名</td>'
					+'<td align="left">'
					+'<input type="text" class="dateEdit" maxlength="30" id="aid" value="'+(record ? record.aid : "")+'"><label class="requre_field">*</label>'
					+'<input type="hidden"  id="uuid" value="'+(record ? record.uuid : "")+'">'
					+'<input type="hidden" id="hpass" value="'+(record ? record.apass : "")+'">'
					+'</td>'
				+'</tr>'
				+'<tr>'
					+'<th align="right">Email地址</td>'
					+'<td align="left"><input type="text" class="dateEdit" maxlength="125" id="amail" value="'+(record ? record.amail : "")+'"><label class="requre_field">*</label></td>'
				+'</tr>'
				;
	if(record) {
		div = div +'<tr>'
					+'<th><label>旧密码</label></th>'
					+'<td align="left"><input  type="password" class="dateEdit" id="oldpwd" autocomplete="off" value="" maxlength="50"/><label class="requre_field">*</label></td>'
				+'</tr>'
				+'<tr>'
					+'<th></th>'
					+'<td align="left"><font color="#768383" style="font-size:12px;">如果要修改密码,请先填写旧密码,如留空,密码保持不变</font></td>'
				+'</tr>';
	}
		div =div +'<tr>'
					+'<th align="right">'+((record) ? "新密码" :"密 码")+'</td>'
					+'<td align="left"><input type="password" class="dateEdit" maxlength="50" id="apass" value=""><label class="requre_field">*</label></td>'
				+'</tr>'
				+'<tr>'
					+'<th align="right">确认密码</td>'
					+'<td align="left"><input type="password" class="dateEdit" maxlength="50" id="newpwd2" ><label class="requre_field">*</label> </td>'
				+'</tr>'
				+'<tr>'
					+'<th align="right">角色选择</td>'
					+'<td align="left"><select id="roleId" style="width: 208px;"></select></td>'
				+'</tr>'
			+'</tbody>'
		+'</table>';
	return div;
};

var repainSelectRole = function(record) {
	$('#roleId').combobox({
		url : 'impl_search/searchObjectList.ajax?qy=&st='+st_role, 
		plain : true, 
		valueField : 'id', 
		textField : 'text',
		value: (record && record.roleId !='0'? record.roleId: "")
	});
};

var editValidator = function(add){
	var record = {
			uuid:$('#uuid').val()
			,aid:$('#aid').val()
			,amail:$('#amail').val()
			,apass:$('#apass').val()
			,apass2:$('#newpwd2').val()
			,roleId:$('#roleId').combobox("getValue")
			,hpass:$('#hpass').val()
			,oldpass:$('#oldpwd').val()
		};
	//验证用户账号
	var error = check_uname(record.aid);
	var msg = null;
	if(error > 0) {
		if (error == 1) {
			msg = ("用户名不能为空");
		} else if (error == 2) {
			msg = ("用户名为4-20位字符");
		} else if (error == 3) {
			msg = ("用户名为4-20位字符");
		} else if (error == 4) {
			msg = ("用户名格式错误");
		}
		$.messager.alert(_msg_sys,msg, "warning");
		return null;
	}
	
	//验证邮箱
	error = check_email(record.amail);
	if(error > 0) {
		msg = null;
		if (error == 1) {
			msg = ("Email不能为空");
		} else if (error == 2) {
			msg = ("邮箱格式错误");
		} else if (error == 3) {
			msg = ("邮箱长度不能超过100位");
		}
		MyUtils.waring(msg);
		return null;
	}
	
	if(add) {
		//验证密码
		if(!MyUtils.isEmpty(record.apass) || !MyUtils.isEmpty(record.apass2)) {
			//新密码验证
			if(!simplePassCheck(record.apass,"密码")){
				return null;
			}
			
			//新密码重复
			if(MyUtils.isEmpty(record.apass2) || (record.apass != record.apass2)) {
				MyUtils.waring("确认密码输入错误");
				return null;
			}
			record.apass = MyUtils.MD5(record.apass);
		} else {
			MyUtils.waring("密码信息不能为空！");
			return null;
		} 
		return MyUtils.toJsonStr(record);
	} else {
		//验证密码
		if(!MyUtils.isEmpty(record.oldpass) || !MyUtils.isEmpty(record.apass) || !MyUtils.isEmpty(record.apass2)) {
			//旧密码验证
			if(MyUtils.isEmpty(record.oldpass) || MyUtils.MD5(record.oldpass) != record.hpass) {
				MyUtils.waring("旧密码输入错误！");
				return null;
			}
			//新密码验证
			if(!simplePassCheck(record.apass,"新密码")){
				return null;
			}
			
			//新密码重复
			if(MyUtils.isEmpty(record.apass2) || (record.apass != record.apass2)) {
				MyUtils.waring("确认密码输入错误");
				return null;
			}
			record.apass = MyUtils.MD5(record.apass);
		} else {
			MyUtils.waring("密码信息不能为空！");
			return null;
		}
		return MyUtils.toJsonStr(record);
	}
	return MyUtils.toJsonStr(record);
};

function check_email(email) {
	if (email == "") {
		return 1;
	}
	var email_reg = /^\w[\w\$\^\(\)\[\]\{\}\.\-\+,]{0,100}@\w+(\.\w{2,4}){1,2}$/;
	if (!email_reg.test(email)) {
		return 2;
	}
	if (email.length > 100) {
		return 3;
	}
	return 0;
}

var check_uname = function(un) {
	var exception = /^[0-9a-zA-Z\,\$\^\(\)\-\_\+\[\]\{\}\u4e00-\u9fa5]{3,20}$/;
	if (MyUtils.isEmpty(un)) {
		return 1;
	}
	if (un.length < 4) {
		return 2;
	}
	if (un.length > 20) {
		return 3;
	}
	if (!exception.test(un)) {
		return 4;
	}
	return 0; 
};

var simplePassCheck = function(password,passName) {
	var check = function(password) {
		if (MyUtils.isEmpty(password)) {
			return 1; // 密码为空
		}
		if (password.length > 20) {
			return 2; // 密码长度超过20
		}
		if (password.length < 6) {
			return 3; // 密码长度小于6
		}
		var isAllSpecial = /[0-9A-Za-z]+$/;
		if (!isAllSpecial.test(password)) {
			return 4; // 密码应该是字母、数字、下划线组成
		}
		return 0;
	};
	
	var showError = function(code,passName) {
		var msg = passName;
		var ok = true;
		if(code == 1) {
			msg +="为空";
		} else if (code == 2 || code == 3) {
			msg +="为6-20位由字母、数字、下划线组成的字符";
		} else if (code == 4) {
			msg +="由字母、数字、下划线组成";
		} else {
			ok = false;
		}
		if(ok) {
			MyUtils.waring(msg);
		}
		return !ok;
	};
	
	var code = check(password);
	return showError(code,passName);
};

/********************************************** 分配权限*****************************/
var checkMenu = function(id){
	var checked = document.getElementById(id).checked;
	$('input[id*="'+id+'"]').attr("checked",checked);
};

var checkMenuItem = function(id,father) {
	var checked = document.getElementById(id).checked;
	$('#'+id).attr("checked",checked);
	
	if(checked) {
		$('#'+father).attr("checked",checked);
		$('input[id*="'+id+'"]').attr("checked",checked);
	} else {
		$('input[id*="'+id+'"]').attr("checked",checked);
		//清除父亲的选中，当父亲没有任何被选中的子项时
//		checkMenu(id);
//		var t = $('input[id*="'+father+'"]:checked');
//		if(t.length == 1) {
//			$('#'+father).attr("checked",false);
//		}
		
	}
};

var chechFunction = function(id,father) {
	var checked = document.getElementById(id).checked;
	$('#'+id).attr("checked",checked);
	if(checked) {
		$('#'+father).attr("checked",checked);
		$('#'+$('#'+father).attr("father")).attr("checked",checked);
	} else {
		//清除父亲的选中，当父亲没有任何被选中的子项时
//		var t = $('input[id*="'+father+'"]:checked');
//		if(t.length == 1) {
//			$('#'+father).attr("checked",false);
//			checkMenuItem(father,$('#'+father).attr("father"));
//		}
	}
};

var createMenu = function(prefix,record) {
	var id =prefix + record.id + "_";
	var menu = '<td class="first-cell" valign="top" align="left">'
			+'<input type="checkbox" onclick="checkMenu(\''+id+'\');" father="0" id="'+id+'" value="'+record.id+'">'
			+record.text
			+'</td><td align="left" style="border-left: 1px solid gray;">';
	
	var children = record.children;
	if(children.length > 0) {
		for(var j = 0; j < children.length; j++){
			menu +=createMenuItem(id,children[j]);
		}
	}
	return menu + '</td>';
};

var createMenuItem = function(prefix,record) {
	var id =prefix + record.id + "_";
	var menuItem = '<div style="float:left;">'
			+'<table cellspacing="1"><tbody>'
			+'<tr>'
			+'<td class="first-cell" align="left" valign="top">'
			+'<input id="'+id+'" type="checkbox" onclick="checkMenuItem(\''+id+'\',\''+prefix+'\');" father="'+prefix+'" title="" value="'+record.id+'" >'
			+record.text
			+'</td>';
			
	var children = record.children;
	if(children.length > 0) {
		menuItem += '<td align="left" style="border-left: 1px solid gray;">';
		for(var j = 0; j < children.length; j++){
			menuItem +=createFunction(id,children[j]);
		}
		menuItem +='</td>';
	}
	menuItem += '</tr><tbody></table></div>';
	return menuItem;
};

var createFunction = function(prefix,record) {
	var id =prefix + record.id + "_";
	var functions = '<div style="width:200px;float:left;">'
			+'<label>'
			+'<input id="'+id+'" type="checkbox" onclick="chechFunction(\''+id+'\',\''+prefix+'\');" title="" value="'+record.id+'" >'
			+record.text
			+'</label>'
			+'</div>';
	return functions;
};

var reopenDatepanel = function() {
	$('#t2').empty();
	$('#t2').append('<table id="dataPanel"></table>');
	loadMemberPanel();
};